﻿using Newtonsoft.Json;
using StackExchange.Redis;

namespace Zws.Redis
{
    public class RedisClient
    {
        private readonly ConnectionMultiplexer redisServer;
        private readonly IDatabase redisDb;

        public RedisClient(RedisConfig config)
        {
            redisServer = ConnectionMultiplexer.Connect($"{config.Ip}:{config.Port}", option =>
            {
                option.Password = config.Password;
            });
            redisDb = redisServer.GetDatabase(config.Db);
        }

        public async Task<bool> SetByKeyAsync(string key, string value)
        {
            return await redisDb.StringSetAsync(key, value);
        }
        public async Task<string?> GetByKeyAsync(string key)
        {
            return await redisDb.StringGetAsync(key);
        }

        public async Task<T?> GetByKeyAsync<T>(string key) where T : class
        {
            var val = await GetByKeyAsync(key);
            return val == null ? default(T) : JsonConvert.DeserializeObject<T>(val);
        }

        public async Task<bool> SetByKeyAsync<T>(string key, T val)
        {
            return await SetByKeyAsync(key, JsonConvert.SerializeObject(val));
        }

        public async Task<bool> IsExistAsync(string key)
        {
            return await redisDb.KeyExistsAsync(key);
        }
        public async Task<bool> DeleteAsync(string key)
        {
            return await redisDb.KeyDeleteAsync(key);
        }
        /// <summary>
        /// 可能有更好的数据结构来处理这种数据？
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <param name="obj"></param>
        /// <returns></returns>
        public async Task AddNodeAsync<T>(string key, T obj)
        {
            var objList = await GetByKeyAsync<List<T>>(key);
            //如果列表不存在自动创建列表
            if (objList == null)
            {
                objList = new List<T>();
            }
            objList.Add(obj);
            await SetByKeyAsync(key, objList);
        }
        public async Task<List<T>?> GetListAsync<T>(string key)
        {
            return await GetByKeyAsync<List<T>>(key);
        }
    }
}
